import { isIE } from "@/utils/broswer";
import { downloadFile } from "@/utils/excel";
import { Ref, ref } from "vue";
import { baseURL } from "@/requests/api/purchase-receipt";
// import { QueryParams } from "@/requests/request";
import { timeFormat } from "@/utils/time";
const setCondition = (selectCondition: any) => {
  console.log("查询条件", selectCondition);
  const queryParams = {
    pageIndex: 1,
    pageSize: 10,
    condition: {
      transactionType: "",
      org: "",
      startTime: "",
      endTime: "",
      account: "",
      materialCode: "",
      source: "",
    },
  };
  const { transactionType, org, dateTimes, account, materialCode, source } =
    selectCondition;
  queryParams.condition.org = org;
  queryParams.condition.transactionType = transactionType;
  if (selectCondition.dateTimes && selectCondition.dateTimes.length > 0) {
    queryParams.condition.startTime = timeFormat(dateTimes[0], "y2s");
    queryParams.condition.endTime = timeFormat(dateTimes[1], "y2s");
  } else {
    queryParams.condition.startTime = "";
    queryParams.condition.endTime = "";
  }
  queryParams.condition.account = account;
  queryParams.condition.materialCode = materialCode;
  queryParams.condition.source = source;
  return queryParams;
};

export const useDownCsv = (
  request: any,
  url?: string,
  params?: any,
  needData?: boolean
) => {
  const exportParams: Ref<object | null> = ref(null);
  if (params) {
    exportParams.value = setCondition(params);
  }
  const exportFile = async () => {
    if (isIE()) {
      window.open(url || `${baseURL}/purchase-receipt/export/excel1`);
    }

    try {
      const res = await request(
        Object.assign({
          responseType: "blob",
        }),
        exportParams.value
      );
      // console.log("返回的excel", res, typeof res);
      const contentDisposition: string = res.headers["content-disposition"]; // 获取文件名,必须服务端放开才行
      console.log("返回的excel", res, contentDisposition);
      let fileName = "模板.csv";
      if (contentDisposition) {
        fileName = decodeURIComponent(contentDisposition.split("=")[1]);
      }
      const data = needData ? res : res.data;
      downloadFile(data as Blob, fileName);
    } catch (error) {
      window.open(url);
      console.log("error", error);
    }
  };
  return {
    exportParams,
    exportFile,
  };
};
